const db = require('../config/database');

class JobSubscription {
  static async create({ userId, keywords, skills }) {
    const [result] = await db.execute(
      'INSERT INTO job_subscriptions (user_id, keywords, skills) VALUES (?, ?, ?)',
      [userId, keywords, skills]
    );
    return result.insertId;
  }

  static async update(id, { keywords, skills }) {
    const [result] = await db.execute(
      'UPDATE job_subscriptions SET keywords = ?, skills = ? WHERE id = ?',
      [keywords, skills, id]
    );
    return result.affectedRows > 0;
  }

  static async getByUserId(userId) {
    const [rows] = await db.execute(
      'SELECT * FROM job_subscriptions WHERE user_id = ?',
      [userId]
    );
    return rows[0];
  }

  static async getMatchingJobs(userId) {
    const subscription = await this.getByUserId(userId);
    if (!subscription) return [];

    const [rows] = await db.execute(
      `SELECT j.* FROM jobs j
       WHERE j.status = "open"
       AND (
         (? IS NULL OR j.title LIKE ? OR j.description LIKE ?)
         AND (? IS NULL OR j.skills LIKE ?)
       )`,
      [
        subscription.keywords,
        `%${subscription.keywords}%`,
        `%${subscription.keywords}%`,
        subscription.skills,
        `%${subscription.skills}%`
      ]
    );
    return rows;
  }
}

module.exports = JobSubscription; 